/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.klikmee.sms.core.base.communicator.telenor.longsms;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import com.klikmee.sms.core.base.communicator.telenor.TelenorCommunicator;
import com.klikmee.sms.core.ws.telenor.client.receivesms.SmsTypeExt;

/**
 * 
 * @author makcro
 */
public class TelenorLongSMSJoiner implements Observer {
	private TelenorCommunicator						communicator	= null;

	private HashMap<String, TelenorLongSMSWrapper>	pendingMessages	= new HashMap<String, TelenorLongSMSWrapper>();

	public void processPart( SmsTypeExt ext ) {
		// resovle message extractor
		String rowMessageText = ext.getMessage();
		LongSMSExtractor longSMSExtractor = LongSMSExtractorFactory.getExtractor( rowMessageText );
		longSMSExtractor.setMessageBody( rowMessageText );

		// prepare data
		String longMessageId = longSMSExtractor.getLongMessageId();
		int sequenceNumber = longSMSExtractor.getSequencePart();
		String messageText = longSMSExtractor.getMessageText();

		// check if this message is mapped already
		if (pendingMessages.containsKey( longMessageId )) {
			// just submit current part to the message
			TelenorLongSMSWrapper longSMSWrapper = pendingMessages.get( longMessageId );
			longSMSWrapper.submitPart( sequenceNumber, messageText );

		}

		else {
			// insert new message into the map
			int totalNumberOfParts = longSMSExtractor.getTotalNumberOfParts();

			TelenorLongSMSWrapper longSMSWrapper = new TelenorLongSMSWrapper( ext, totalNumberOfParts, longMessageId );
			longSMSWrapper.submitPart( sequenceNumber, messageText );
			// map the message
			pendingMessages.put( longMessageId, longSMSWrapper );
		}
	}

	public TelenorLongSMSJoiner() {

	}

	public void update( Observable o, Object arg ) {
		// cast object types
		if (o instanceof TelenorLongSMSWrapper) {
			TelenorLongSMSWrapper longMessage = (TelenorLongSMSWrapper) o;

			// cast argument
			if (arg instanceof SmsTypeExt) {
				SmsTypeExt message = (SmsTypeExt) arg;

				// forward message to communicator
				List<SmsTypeExt> messages = new ArrayList<SmsTypeExt>();
				messages.add( message );
				communicator.onNewMessages( messages );

				// remove message from the
				String messageId = longMessage.getMessageId();
				pendingMessages.remove( messageId );
			}

		}

		return;
	}

	public void setCommunicator( TelenorCommunicator communicator ) {
		this.communicator = communicator;
	}
}
